import os.path
import tkinter as tk
from tkinter import scrolledtext
import subprocess


class CmdTools:
    PER_ROW_BUTTON_NUMS = 2
    ini_file = 'cmd_tools.ini'
    default_cmd_map = {
        '当前目录': 'cd && dir',
        '目录内容': 'dir',
        '网络信息1a': 'ipconfig',
        '网络信息2b': 'ipconfig',
        '网络信息3': 'ipconfig',
        '网络信息4': 'ipconfig',
    }

    @staticmethod
    def get_cmd_map():
        cmd_map = {}
        if not os.path.exists(CmdTools.ini_file):
            with open(CmdTools.ini_file, 'w', encoding='utf-8') as f:
                for k, v in CmdTools.default_cmd_map.items():
                    line = f'{k}: {v}\n'
                    f.write(line)
            return CmdTools.default_cmd_map
        with open(CmdTools.ini_file, 'r', encoding='utf-8') as f:
            for line in f.readlines():
                line = line.strip()
                if not line or ':' not in line or line.startswith('#'):
                    continue
                line = line.split(':', maxsplit=2)
                if len(line) != 2:
                    continue
                cmd_map[line[0]] = line[1]
        return cmd_map

    @staticmethod
    def run_command(cmd):
        try:
            result = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT, encoding='gbk')
        except subprocess.CalledProcessError as e:
            result = e.output
        return result

    @staticmethod
    def update_output(cmd, output_text):
        pwd = CmdTools.run_command('cd').strip()
        res = CmdTools.run_command(cmd)
        # output_text.delete(1.0, tk.END)
        result = f'{pwd}>{cmd}\n{res}'
        output_text.insert(tk.END, result)

    @staticmethod
    def ui(root, cmd_map):
        # ---------------- 左侧按钮区域 + 滚动 ----------------
        left_frame = tk.Frame(root)
        left_frame.grid(row=0, column=0, sticky="ns")

        canvas = tk.Canvas(left_frame, width=250)
        scrollbar = tk.Scrollbar(left_frame, orient="vertical", command=canvas.yview)
        scrollable_frame = tk.Frame(canvas)

        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )

        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # ---------------- 右侧输出框 ----------------
        right_frame = tk.Frame(root)
        right_frame.grid(row=0, column=1, sticky="nsew")
        right_frame.grid_rowconfigure(0, weight=1)
        right_frame.grid_columnconfigure(0, weight=1)

        output_text = scrolledtext.ScrolledText(right_frame, wrap=tk.WORD, font=("Courier New", 10))
        output_text.grid(row=0, column=0, sticky="nsew")

        # 生成按钮：每行 3 个
        col_count = CmdTools.PER_ROW_BUTTON_NUMS
        for index, (btn_text, cmd) in enumerate(cmd_map.items()):
            row = index // col_count
            col = index % col_count
            button = tk.Button(scrollable_frame, text=btn_text, width=15,
                               command=lambda c=cmd, output=output_text: CmdTools.update_output(c, output))
            button.grid(row=row, column=col, padx=5, pady=5, sticky="ew")

    @staticmethod
    def get_root():
        # 创建主窗口
        root = tk.Tk()
        root.title("CMD工具v1.0.0.0")
        root.geometry("900x600")
        root.minsize(600, 400)
        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(1, weight=1)
        return root

    @staticmethod
    def main():
        root = CmdTools.get_root()
        cmd_map = CmdTools.get_cmd_map()
        CmdTools.ui(root, cmd_map)
        # 运行主循环
        root.mainloop()


if __name__ == '__main__':
    CmdTools.main()
